<?php

namespace App\Repository\UpThree;

use App\Api\CatchOrder\DouYin;
use App\Api\CatchOrder\Kwai;
use App\Api\CatchOrder\Pdd;
use App\Api\Three\DouYinOld;
use App\Jobs\GetOrderStatus;
use App\Jobs\OrderSubmit;
use App\Repository\BaseRepository;
use App\Repository\CatchConf\DouYinCatchRepository;
use App\Repository\CatchConf\DouYinRepository;
use App\Repository\CatchConf\KWaiCatchRepository;
use App\Repository\CatchConf\KWaiRepository;
use App\Repository\CatchConf\PddCatchRepository;
use App\Repository\CatchConf\PddRepository;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

//KWaiRepository

//KWaiRepository

//KWaiRepository

// use function GuzzleHttp\json_encode;

class GetThreeOrderRepostition extends BaseRepository
{
    public $log;

    public function __construct()
    {
        $this->log = new Logger('ChinnelLog');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ChinnelLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

    public function getOrder($data)
    {
        if (empty($data['type'])) {
            return $this->returnMsg(11, '类型为空');
        }
        $type = $data['type'];
        $return = [];
        switch ($type) {
            case 'douyin':
                // 抖音订单
                $return = $this->getDouYinOrder($data);
                break;
            case 'kwai':
                // 快手订单
                $return = $this->getKwaiOrder($data);
                break;
            case 'pdd':
                $return = $this->getPddOrder($data);
                break;
        }
        return $return;
    }

    // 获取订单  抓取抖音的订单
    public function getDouYinOrder($data = array())
    {
        $this->log->info('抖音抓取时的数据:' . json_encode($data));
        // 根据推送过来的信息 获取订单详情 需要对接
        if (empty($data['shop_id'])) {
            return $this->returnMsg(103, '抖音信息为空');
        }
        $douyinRModel = new DouYinRepository();
        $whereDouYin = [
            'app_shop_id' => $data['shop_id'],
            'nums' => 1
        ];
        $resDouYin = $douyinRModel->getOne($whereDouYin);

        if (empty($resDouYin)) {
            return $this->returnMsg(104, '未查询抖音配置');
        }
        if (!empty($data['pid'])) {
            $isTrueSub = Cache::get($data['pid'] . '_douyinzhuandan_vatch_' . $data['shop_id']);
            if (!empty($isTrueSub) && $isTrueSub == 1) {
                // var_dump($data);
                dispatch(new OrderSubmit($data, 'catchOrder', 180))->onQueue('TaskOrderSubmitDispose');
                return $this->returnMsg(105, '在运行中请稍后在运行');;
            }
            Cache::put($data['pid'] . '_douyinzhuandan_vatch_' . $data['shop_id'], 1, Carbon::now()->addMinutes(2));
        }
        // 查询抖音的数据
        $douyinModel = new DouYin($resDouYin->app_shop_id, $resDouYin->app_key, $resDouYin->app_secret);

        $resDouYinDetails = $douyinModel->orderDetails($data);
        if (empty($resDouYinDetails['data'][0])) {
            return $this->returnMsg(200, '未查询到订单信息');
        }
        $disUserId = '';
        $disUserName = '';
        $resDouYinDetail = $resDouYinDetails['data'][0];
        if (!empty($resDouYinDetail['author_id'])) {
            $whereDis = [
                ['supplier_id', '=', $resDouYin->shop_id],
                ['dist_code', 'like', '%,' . $resDouYinDetail['author_id'] . ',%'],
            ];
            $disArr = DB::table('supplier')->where($whereDis)->select(['name', 'shop_id'])->first();
            if ($disArr) {
                $disUserId = $disArr->shop_id;
                $disUserName = $disArr->name;
            }
        }
        $orderData = [
            'source' => 1,  // 数据来源
            'goods_code' => $resDouYinDetail['product'],
            'name' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['user_name'] : '',
            'identity' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['card_num'] : '',
            'contact' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['user_phone'] : '',
            'province' => $resDouYinDetail['province'],
            'city' => $resDouYinDetail['city'],
            'area' => $resDouYinDetail['area'],
            'address' => (!empty($resDouYinDetail['street']) ? $resDouYinDetail['street'] : '') . (($resDouYinDetails['code'] == 200) ? $resDouYinDetail['addr'] : ''),
            'shop_id' => $resDouYin->shop_id,
            'dist_orderno' => $resDouYinDetail['order_num'],
            'dist_id' => $resDouYin->id,
            'dist_name' => !empty($resDouYin->remark) ? $resDouYin->remark : '',
            'author_id' => $resDouYinDetail['author_id'],
            'author_name' => $resDouYinDetail['author_name'],
            'remark' => $resDouYinDetail['c_biz_desc'],
            'douyin_id' => !empty($disUserId) ? $disUserId : 0, //抖音信息
            'douyin_name' => !empty($disUserName) ? $disUserName : '', //抖音店铺名称
        ];
        // 存入到订单表中
        $res = [];
        $orderData['status'] = 50;
        $models = new DouYinCatchRepository();
        $isTrueOrder = $models->getOne(['dist_orderno' => $orderData['dist_orderno']]);
        if ($isTrueOrder) {
            // 判断用户名和手机号 身份证号是否为空
            if (!empty($isTrueOrder->user_name) && !empty($isTrueOrder->user_phone) && !empty($isTrueOrder->user_phone)) {
                return ['status' => 101, 'msg' => '用户已提交'];
            }

            // if ($isTrue) {
            //     return ['status' => 100, 'msg' => '订单重复'];
            // }
        }
        if (!empty($resDouYinDetails['code']) && $resDouYinDetails['code'] == 200) {
            $model = new MainOrderRepostition();
            $orderDatas = $orderData;
            if (!empty($orderDatas['douyin_id'])) {
                $orderDatas['shop_id'] = $orderDatas['douyin_id'];
                $orderDatas['source'] = 6;
            }
            $res = $model->orderSubmit($orderDatas);
            $orderData['status'] = 0;
        }
        $orderData['three_msg'] = !empty($res['msg']) ? $res['msg'] : '订单已关闭';
        if (!empty($res['code']) && $res['code'] != 200) {
            $orderData['status'] = 60;
        }
        $orderData['package_name'] = !empty($resDouYinDetail['package_name']) ? $resDouYinDetail['package_name'] : '';
        $orderData['created_at'] = !empty($resDouYinDetail['created_at']) ? $resDouYinDetail['created_at'] : '';
        $orderData['douyin_status_name'] = !empty($resDouYinDetail['douyin_status_name']) ? $resDouYinDetail['douyin_status_name'] : '';
        $returnId = '';
        if ($isTrueOrder) {
            $returnId = $orderData['dist_orderno'];
            $isTrue = $models->edit(['dist_orderno' => $orderData['dist_orderno']], $orderData);
        } else {
            $insertData = $models->add($orderData);
        }
        // 需要提交到 老系统的抖音里面
        if (!empty($insertData['data']['id'])) {
            $returnId = $orderData['dist_orderno'];

            // 判断提交时间 48小时限制 抖店的订单
            //strtotime(date('Y-m-d 09:00:00', strtotime('+1 days')))
            // $times = 46 * 60 * 60; // 默认 46h后 处理
            // dispatch(new OrderSubmit($orderData['dist_orderno'], 'smsAndPushOrder', $times))->onQueue('TaskOrderSubmitDispose');
        }
        if (!empty($returnId) && !empty($resDouYinDetails['code']) && $resDouYinDetails['code'] == 200) {
            dispatch(new OrderSubmit($returnId, 'catchDouYinOld'))->onQueue('TaskOrderSubmitDispose');
        }

        return $res;
    }

    // 快手抓单
    public function getKwaiOrder($data)
    {
        $this->log->info('快手抓取时的数据:' . json_encode($data));
        // 根据推送过来的信息 获取订单详情 需要对接
        if (empty($data['shop_id'])) {
            return $this->returnMsg(103, '抖音信息为空');
        }
        $douyinRModel = new KWaiRepository();
        // 这个参数可能会失败
        $whereDouYin = [
            'app_key' => $data['shop_id'],
            'nums' => 1
        ];
        $resDouYin = $douyinRModel->getOne($whereDouYin);
        // var_dump($resDouYin);
        if (empty($resDouYin)) {
            return $this->returnMsg(104, '未查询快手配置');
        }
        if (!empty($data['pid'])) {
            $isTrueSub = Cache::get($data['pid'] . '_kwaizhuandan_vatch_' . $data['shop_id']);
            if (!empty($isTrueSub) && $isTrueSub == 1) {
                // var_dump($data);
                dispatch(new OrderSubmit($data, 'catchOrder', 180))->onQueue('TaskOrderSubmitDispose');
                return $this->returnMsg(105, '在运行中请稍后在运行');;
            }
            Cache::put($data['pid'] . '_douyinzhuandan_vatch_' . $data['shop_id'], 1, Carbon::now()->addMinutes(2));
        }
        // 查询抖音的数据
        $douyinModel = new Kwai($resDouYin->app_shop_id, $resDouYin->app_key, $resDouYin->app_secret, $resDouYin->sign_secret);

        $resDouYinDetails = $douyinModel->getOrderDetail($data);
        // var_dump($resDouYinDetails, 777777777);
        if (empty($resDouYinDetails)) {
            return $this->returnMsg(200, '未查询到订单信息');
        }
        $disUserId = '';
        $disUserName = '';
        $resDouYinDetail = $resDouYinDetails;
        if (!empty($resDouYinDetail['author_id'])) {
            $whereDis = [
                ['supplier_id', '=', $resDouYin->shop_id],
                ['dist_code', 'like', '%,' . $resDouYinDetail['author_id'] . ',%'],
            ];
            $disArr = DB::table('supplier')->where($whereDis)->select(['name', 'shop_id'])->first();
            if ($disArr) {
                $disUserId = $disArr->shop_id;
                $disUserName = $disArr->name;
            }
        }
        $orderData = [
            'source' => 12,  // 数据来源
            'goods_code' => $resDouYinDetail['product'],
            'name' => (!empty($resDouYinDetail['user_name'])) ? $resDouYinDetail['user_name'] : '',
            'identity' => (!empty($resDouYinDetail['card_num'])) ? $resDouYinDetail['card_num'] : '',
            'contact' => (!empty($resDouYinDetail['user_phone'])) ? $resDouYinDetail['user_phone'] : '',
            'province' => $resDouYinDetail['province'],
            'city' => $resDouYinDetail['city'],
            'area' => $resDouYinDetail['area'],
            'address' => (!empty($resDouYinDetail['street']) ? $resDouYinDetail['street'] : '') . ((!empty($resDouYinDetail['addr'])) ? $resDouYinDetail['addr'] : ''),
            'shop_id' => $resDouYin->shop_id,
            'dist_orderno' => $resDouYinDetail['order_num'],
            'dist_id' => $resDouYin->id,
            'dist_name' => !empty($resDouYin->remark) ? $resDouYin->remark : '',
            'author_id' => $resDouYinDetail['author_id'],
            'author_name' => $resDouYinDetail['author_name'],
            'remark' => $resDouYinDetail['c_biz_desc'],
            'douyin_id' => !empty($disUserId) ? $disUserId : 0, //抖音信息
            'douyin_name' => !empty($disUserName) ? $disUserName : '', //抖音店铺名称
        ];
        // 存入到订单表中
        $res = [];
        $orderData['status'] = 50;
        $models = new KWaiCatchRepository();
        $isTrueOrder = $models->getOne(['dist_orderno' => $orderData['dist_orderno']]);
        if ($isTrueOrder) {
            // 判断用户名和手机号 身份证号是否为空
            if (!empty($isTrueOrder->user_name) && !empty($isTrueOrder->user_phone) && !empty($isTrueOrder->user_phone)) {
                return ['status' => 101, 'msg' => '用户已提交'];
            }

            // if ($isTrue) {
            //     return ['status' => 100, 'msg' => '订单重复'];
            // }
        }
        if (!empty($resDouYinDetails['code']) && $resDouYinDetails['code'] == 200) {
            $model = new MainOrderRepostition();
            // 暂时不提交
            // $orderDatas = $orderData;
            // // if (!empty($orderDatas['douyin_id'])) {
            // //     $orderDatas['shop_id'] = $orderDatas['douyin_id'];
            // //     $orderDatas['source'] = 6;
            // // }
            // $res = $model->orderSubmit($orderDatas);
            // $orderData['status'] = 0;
        }
        $orderData['three_msg'] = !empty($res['msg']) ? $res['msg'] : '订单已关闭';
        if (!empty($res['code']) && $res['code'] != 200) {
            $orderData['status'] = 60;
        }
        $orderData['package_name'] = !empty($resDouYinDetail['package_name']) ? $resDouYinDetail['package_name'] : '';
        $orderData['created_at'] = !empty($resDouYinDetail['created_at']) ? $resDouYinDetail['created_at'] : '';
        $orderData['douyin_status_name'] = !empty($resDouYinDetail['douyin_status_name']) ? $resDouYinDetail['douyin_status_name'] : '';
        $returnId = '';
        if ($isTrueOrder) {
            $returnId = $orderData['dist_orderno'];
            $isTrue = $models->edit(['dist_orderno' => $orderData['dist_orderno']], $orderData);
        } else {
            $insertData = $models->add($orderData);
        }
        // 需要提交到 老系统的抖音里面
        if (!empty($insertData['data']['id'])) {
            $returnId = $orderData['dist_orderno'];

            // 判断提交时间 48小时限制 抖店的订单
            //strtotime(date('Y-m-d 09:00:00', strtotime('+1 days')))
            // $times = 46 * 60 * 60; // 默认 46h后 处理
            // dispatch(new OrderSubmit($orderData['dist_orderno'], 'smsAndPushOrder', $times))->onQueue('TaskOrderSubmitDispose');
        }
        // if (!empty($returnId) && !empty($resDouYinDetails['code']) && $resDouYinDetails['code'] == 200) {
        //     dispatch(new OrderSubmit($returnId, 'catchDouYinOld'))->onQueue('TaskOrderSubmitDispose');
        // }

        return !empty($res) ? $res : ['code' => 100, 'msg' => '无提交'];
    }

    // 拼多多 抓单  消息推送 暂时不用
    public function getPddOrder($data)
    {
        $this->log->info('拼多多抓取时的数据:' . json_encode($data));
        return ['code' => 100, 'msg' => '暂时不使用'];
        // 根据推送过来的信息 获取订单详情 需要对接
        if (empty($data['shop_id'])) {
            return $this->returnMsg(103, '拼多多店铺信息为空');
        }
        // 记录的是 配置文件
        $douyinRModel = new PddRepository();
        // 这个参数可能会失败
        $whereDouYin = [
            'app_key' => $data['shop_id'],
            'nums' => 1
        ];
        $resDouYin = $douyinRModel->getOne($whereDouYin);
        // var_dump($resDouYin);
        if (empty($resDouYin)) {
            return $this->returnMsg(104, '未查询快手配置');
        }
        if (!empty($data['pid'])) {
            $isTrueSub = Cache::get($data['pid'] . '_pddzhuandan_vatch_' . $data['shop_id']);
            if (!empty($isTrueSub) && $isTrueSub == 1) {
                // var_dump($data);
                dispatch(new OrderSubmit($data, 'catchOrder', 180))->onQueue('TaskOrderSubmitDispose');
                return $this->returnMsg(105, '在运行中请稍后在运行');;
            }
            Cache::put($data['pid'] . '_pddzhuandan_vatch_' . $data['shop_id'], 1, Carbon::now()->addMinutes(2));
        }
        // 查询抖音的数据
        $douyinModel = new Pdd($resDouYin->app_shop_id, $resDouYin->app_key, $resDouYin->app_secret, $resDouYin->sign_secret);

        $resDouYinDetails = $douyinModel->getOrderDetail($data);
        // var_dump($resDouYinDetails, 777777777);
        if (empty($resDouYinDetails)) {
            return $this->returnMsg(200, '未查询到订单信息');
        }
        $disUserId = '';
        $disUserName = '';
        $resDouYinDetail = $resDouYinDetails;
        if (!empty($resDouYinDetail['author_id'])) {
            $whereDis = [
                ['supplier_id', '=', $resDouYin->shop_id],
                ['dist_code', 'like', '%,' . $resDouYinDetail['author_id'] . ',%'],
            ];
            $disArr = DB::table('supplier')->where($whereDis)->select(['name', 'shop_id'])->first();
            if ($disArr) {
                $disUserId = $disArr->shop_id;
                $disUserName = $disArr->name;
            }
        }
        // 拼多多
        $orderData = [
            'source' => 11,  // 数据来源
            'goods_code' => $resDouYinDetail['product'],
            'name' => (!empty($resDouYinDetail['user_name'])) ? $resDouYinDetail['user_name'] : '',
            'identity' => (!empty($resDouYinDetail['card_num'])) ? $resDouYinDetail['card_num'] : '',
            'contact' => (!empty($resDouYinDetail['user_phone'])) ? $resDouYinDetail['user_phone'] : '',
            'province' => $resDouYinDetail['province'],
            'city' => $resDouYinDetail['city'],
            'area' => $resDouYinDetail['area'],
            'address' => (!empty($resDouYinDetail['street']) ? $resDouYinDetail['street'] : '') . ((!empty($resDouYinDetail['addr'])) ? $resDouYinDetail['addr'] : ''),
            'shop_id' => $resDouYin->shop_id,
            'dist_orderno' => $resDouYinDetail['order_num'],
            'dist_id' => $resDouYin->id,
            'dist_name' => !empty($resDouYin->remark) ? $resDouYin->remark : '',
            'author_id' => $resDouYinDetail['author_id'],
            'author_name' => $resDouYinDetail['author_name'],
            'remark' => $resDouYinDetail['c_biz_desc'],
            'douyin_id' => !empty($disUserId) ? $disUserId : 0, //抖音信息
            'douyin_name' => !empty($disUserName) ? $disUserName : '', //抖音店铺名称
        ];
        // 存入到订单表中
        $res = [];
        $orderData['status'] = 50;
        $models = new PddCatchRepository();
        $isTrueOrder = $models->getOne(['dist_orderno' => $orderData['dist_orderno']]);
        if ($isTrueOrder) {
            // 判断用户名和手机号 身份证号是否为空
            if (!empty($isTrueOrder->user_name) && !empty($isTrueOrder->user_phone) && !empty($isTrueOrder->user_phone)) {
                return ['status' => 101, 'msg' => '用户已提交'];
            }

            // if ($isTrue) {
            //     return ['status' => 100, 'msg' => '订单重复'];
            // }
        }
        if (!empty($resDouYinDetails['code']) && $resDouYinDetails['code'] == 200) {
            $model = new MainOrderRepostition();
            // 暂时不提交
            // $orderDatas = $orderData;
            // // if (!empty($orderDatas['douyin_id'])) {
            // //     $orderDatas['shop_id'] = $orderDatas['douyin_id'];
            // //     $orderDatas['source'] = 6;
            // // }
            // $res = $model->orderSubmit($orderDatas);
            // $orderData['status'] = 0;
        }
        $orderData['three_msg'] = !empty($res['msg']) ? $res['msg'] : '订单已关闭';
        if (!empty($res['code']) && $res['code'] != 200) {
            $orderData['status'] = 60;
        }
        $orderData['package_name'] = !empty($resDouYinDetail['package_name']) ? $resDouYinDetail['package_name'] : '';
        $orderData['created_at'] = !empty($resDouYinDetail['created_at']) ? $resDouYinDetail['created_at'] : '';
        $orderData['douyin_status_name'] = !empty($resDouYinDetail['douyin_status_name']) ? $resDouYinDetail['douyin_status_name'] : '';
        $returnId = '';
        if ($isTrueOrder) {
            $returnId = $orderData['dist_orderno'];
            $isTrue = $models->edit(['dist_orderno' => $orderData['dist_orderno']], $orderData);
        } else {
            $insertData = $models->add($orderData);
        }

        return !empty($res) ? $res : ['code' => 100, 'msg' => '无提交'];
    }

    // 拼多多 抓单列表的信息  半个小时抓取一次  拼多多表的总的查询
    public function getPddListAll()
    {
        // 拼多多列表 批量读取  半个小时 读取一次
        // DB::connection()->enableQueryLog();
        $res = DB::table('pdd_conf')->where('status', '1')->orderBy('id', 'desc')->get();
        // $logs = DB::getQueryLog();
        // var_dump($logs);
        if (!empty($res)) {
            if (!empty($res)) {
                foreach ($res as $key => $v) {
                    // 启动单个渠道的循环
                    $data = json_decode(json_encode($v), true);
                    $times = 20;
                    // var_dump($data);
                    // if (!empty($v['interval_time'])) {
                    //     $times = $v['interval_time'] * 60;
                    // }
                    dispatch(new GetOrderStatus($data, 'getPddListAllOne', $times))->onQueue('TaskGetOrderStatusDispose');
                    // return $this->returnMsg(200, '分页读取' . $page);
                }
            }
        }
        // 启动三个小时 一个循环
        $time = 5 * 60; // 30分钟更新一次
        dispatch(new GetOrderStatus(1, 'getPddListAll', $time))->onQueue('TaskGetOrderStatusDispose');
        return $this->returnMsg(200, '运行完成');
    }

    // 拼多多 抓单表的单个查询 半个小时一次
    public function getPddListAllOne($data = array())
    {
        $times = 5;
        if (!empty($v['interval_time'])) {
            $times = $v['interval_time'] * 60;
        }
        $model = new Pdd($data['params'], $data['client_id'], $data['client_secret'], $data['sign_secret'], $data['id'], $times);
        $res = $model->async();
        $this->log->info('传递参数:' . json_encode($data) . '返回参数:' . json_encode($res));
        return $res;
    }

    //抖音漏单抓取
    public function getMissingOrder($page = 0)
    {
        // var_dump($page, 999999999999);
        $page = 0;
        $nums = 10;
        // DB::connection()->enableQueryLog();
        $time = time() - (30 * 60);
        $times = date('Y-m-d H:i:s', $time);
        $where = [
            ['created_at', '<=', $times]
        ];
        $data = DB::table('dd_no_submit_order')->where('is_back', 0)->where($where)->skip($page * $nums)->take($nums)->get();
        // $sql = DB::getQueryLog();
        // var_dump($sql);
        // die();
        if (!empty($data)) {
            foreach ($data as $key => $v) {
                $v = json_decode(json_encode($v), true);
                $shopRes = DB::table('douyin_conf')->where('app_shop_id', $v['shop_id'])->first();
                if (!$shopRes) {
                    continue;
                }
                $disUserId = '';
                $disUserName = '';
                if (!empty($v['author_id'])) {
                    $whereDis = [
                        ['supplier_id', '=', $shopRes->shop_id],
                        ['dist_code', 'like', '%,' . $v['author_id'] . ',%'],
                    ];
                    $disArr = DB::table('supplier')->where($whereDis)->select(['name', 'shop_id'])->first();
                    if ($disArr) {
                        $disUserId = $disArr->shop_id;
                        $disUserName = $disArr->name;
                    }
                }
                $data = [
                    'source' => 1,  // 数据来源
                    'goods_code' => $v['product'],
                    'name' => $v['user_name'],
                    'identity' => $v['card_num'],
                    'contact' => $v['user_phone'],
                    'province' => $v['province'],
                    'city' => $v['city'],
                    'area' => $v['area'],
                    'address' => (!empty($v['street']) ? $v['street'] : '') . ($v['addr']),
                    'shop_id' => $shopRes->shop_id,
                    'dist_orderno' => $v['order_num'],
                    'dist_id' => $shopRes->id,
                    'dist_name' => !empty($shopRes->remark) ? $shopRes->remark : '',
                    'author_id' => $v['author_id'],
                    'author_name' => $v['author_name'],
                    'remark' => $v['c_biz_desc'],
                    'package_name' => $v['package_name'],
                    'created_at' => $v['created_at'],
                    'douyin_status_name' => $v['douyin_status_name'],
                    'douyin_id' => !empty($disUserId) ? $disUserId : 0, //抖音信息
                    'douyin_name' => !empty($disUserName) ? $disUserName : '', //抖音店铺名称
                ];
                $res = $this->handleData($data);
                if ($res) {
                    DB::table('dd_no_submit_order')->where('id', $v['id'])->update(['is_back' => 1]);
                }
            }
            $page += 1;
        }
        if (empty($data) || count($data) < $nums) {
            $page = 0;
        }

        if ($page > 0) {
            $this->getMissingOrder($page);
        }
        return 1;
    }

    // 抖音单条数据处理
    public function handleData($data = [])
    {
        $model = new DouYinCatchRepository();
        $where = [
            'dist_orderno' => $data['dist_orderno'],
        ];
        //查询某个数据是否存在
        $res = $model->getOne($where);
        if ($res) {
            if (!empty($res->contact)) {
                // var_dump($where);
                return 1;
            }
            $update = $model->edit($where, $data);
            // dispatch(new OrderSubmit($data['dist_orderno'], 'catchDouYinOld'))->onQueue('TaskOrderSubmitDispose');
            // 判断提交时间 48小时限制 抖店的订单
            //$times = 46 * 60 * 60; // 默认 46h后 处理
            //dispatch(new OrderSubmit($data['dist_orderno'], 'smsAndPushOrder', $times))->onQueue('TaskOrderSubmitDispose');
            return $update;
        }
        // 存入到订单表中
        $res = [];
        $data['status'] = 51;
        if (true) {
            $datas = $data;
            if (!empty($data['douyin_id'])) {
                $datas['shop_id'] = $data['douyin_id'];
                $datas['source'] = 6;
            }
            // var_dump($datas, 3333333333);
            $models = new MainOrderRepostition();
            $res = $models->orderSubmit($datas);
            $data['status'] = 0;
        }
        $data['three_msg'] = !empty($res['msg']) ? $res['msg'] : '订单已关闭';
        if (!empty($res['code']) && $res['code'] != 200) {
            $data['status'] = 60;
        }
        // var_dump($data);
        $insertData = $model->add($data);
        if (!empty($insertData['data']['id'])) {
            // dispatch(new OrderSubmit($data['dist_orderno'], 'catchDouYinOld'))->onQueue('TaskOrderSubmitDispose');
            // 判断提交时间 48小时限制 抖店的订单
            //$times = 46 * 60 * 60; // 默认 46h后 处理
            //dispatch(new OrderSubmit($data['dist_orderno'], 'smsAndPushOrder', $times))->onQueue('TaskOrderSubmitDispose');
        }
        return 1;
    }

    //  不往老系统提交抖店的订单信息了
    public function catchDouYinOld($data)
    {
        return [];
        $model = new DouYinOld();
        $where = [
            'dist_orderno' => $data['orderno']
        ];
        return $model->orderSubmit($where);
    }

    // 抓取的订单 修改商品然后重新提交
    public function douyinNewSubmit($data = array())
    {
        $data = [
            'dist_orderno' => $data['dist_orderno'],
        ];
        // 查询数据
        $models = new DouYinCatchRepository();
        $isTrueOrder = $models->getOne(['dist_orderno' => $data['dist_orderno']]);
        if ($isTrueOrder) {
            $isTrueOrder = json_decode(json_encode($isTrueOrder), true);
        }
        $model = new MainOrderRepostition();
        $orderDatas = $isTrueOrder;
        $orderDatas['source'] = 1;
        if (!empty($orderDatas['douyin_id'])) {
            $orderDatas['shop_id'] = $orderDatas['douyin_id'];
            $orderDatas['source'] = 6;
        }
        // var_dump($orderDatas);
        // die();
        $update = [
            'three_msg' => '该订单不能重复提交',
            // 'status' => 0
        ];
        if ($isTrueOrder >= 50) {
            $res = $model->orderSubmit($orderDatas);
            $update['status'] = 0;
            $update['three_msg'] = '已重提';
        }
        if (!empty($res['code']) && $res['code'] != 200) {
            $update['status'] = 60;
            $update['three_msg'] = !empty($res['msg']) ? $res['msg'] : '重提失败';
        }
        $models->edit(['dist_orderno' => $data['dist_orderno']], $update);
        return $res;
    }

    // 抓取的订单 修改商品然后重新提交
    public function pddNewSubmit($data = array())
    {
        $data = [
            'dist_orderno' => $data['dist_orderno'],
        ];
        // 查询数据
        $models = new PddCatchRepository();
        $isTrueOrder = $models->getOne(['dist_orderno' => $data['dist_orderno']]);
        if ($isTrueOrder) {
            $isTrueOrder = json_decode(json_encode($isTrueOrder), true);
        }
        $model = new MainOrderRepostition();
        $orderDatas = $isTrueOrder;
        $orderDatas['source'] = 1;
        if (!empty($orderDatas['douyin_id'])) {
            $orderDatas['shop_id'] = $orderDatas['douyin_id'];
            $orderDatas['source'] = 6;
        }
        // var_dump($orderDatas);
        // die();
        $update = [
            'three_msg' => '该订单不能重复提交',
            // 'status' => 0
        ];
        if ($isTrueOrder >= 50) {
            $res = $model->orderSubmit($orderDatas);
            $update['status'] = 0;
            $update['three_msg'] = '已重提';
        }
        if (!empty($res['code']) && $res['code'] != 200) {
            $update['status'] = 60;
            $update['three_msg'] = !empty($res['msg']) ? $res['msg'] : '重提失败';
        }
        $models->edit(['dist_orderno' => $data['dist_orderno']], $update);
        return $res;
    }

    public function getLianTongBack($page = 1)
    {
        if (empty($page) || $page < 1) {
            $page = 1;
        }
        $where = [
            ['is_run', '=', 1],
            // ['created_at','>','2023-07-29 00:00:00']
        ];
        $nums = 2;
        $skip = ($page - 1) * $nums;
        $datas = DB::table('liantong_push_log')->where($where)->take($nums)->skip(($skip))->orderBy('id', 'desc')->get();
        if (!empty($datas)) {
            foreach ($datas as $key => $v) {
                $v = json_decode(json_encode($v), true);
                $this->editOrdersStatus($v);
                DB::table('liantong_push_log')->where(['id' => $v['id']])->update(['is_run' => 2]);
            }
        }
        // var_dump($datas,555555555);
        // var_dump(count($datas),555555555);
        if (count($datas) >= $nums) {
            $page++;
            dispatch(new GetOrderStatus($page, 'liantongBackApi', 5))->onQueue('TaskGetOrderStatusDispose');
        }
        return '运行完成';
    }

    public function editOrdersStatus($getData)
    {
        $statusData = [
            '1' => '40', //已激活
            '2' => '50', // 待处理
            '3' => '50', //代发货
            '4' => '60', // 销户
            '6' => '40', // 订单取消
            'C1' => '40', // 已签收
            'E0' => '20', // 已发货
        ];
        if (empty($statusData[$getData['state']])) {
            return false;
        }
        // $editData = [
        //     'status' => !empty($statusData[$getData['orderState']]) ? $statusData[$getData['orderState']] : '50',
        //     'express_company' => !empty($getData['logisticsCompanies'])?$getData['logisticsCompanies']:'',
        //     'express_number' => !empty($getData['logisticsNo'])?$getData['logisticsNo']:'',
        //     'three_msg' => $getData['describe'],
        //     'iccid' => $getData['phoneNum'],
        //     'first_status' => !empty($getData['balanceOne']) ? '1' : '0',
        //     'first_status_desc' => !empty($getData['balanceOne']) ? ($getData['balanceOne'] / 100) : '0',
        //     'imei' => !empty($getData['sim'])?$getData['sim']:''
        //   ];
        $editData = [];
        if (!empty($editData['mobile'])) {
            $editData['iccid'] = $editData['mobile'];
        }
        if (!empty($getData['state']) && $getData['state'] == 6) {
            $editData['first_money'] = $editData['first_status_desc'] = (int)$getData['lgtsId'] / 100;
            if ($editData['first_money'] > 0) {
                $editData['first_status'] = 1;
                $editData['status'] = 41;
                $editData['first_status_at'] = date('Y-m-d H:i:s');
            }
        }
        if (!empty($getData['state']) && $getData['state'] == 'E0' && !empty($getData['lgtsId'])) {
            $editData['express_number'] = trim($getData['lgtsId']);
        }
        if (!empty($getData['sim'])) {
            $editData['imei'] = $getData['sim'];
        }
        if (empty($editData) || empty($getData['order'])) {
            return false;
        }
        $where = ['sup_orderno' => $getData['order']];
        $model = new MainOrderRepostition();
        $descData = [];
        // var_dump($editData,1111111);die();
        // var_dump($where,55555555);
        $res = $model->followOrderStatus($where, $editData, $descData);
        $this->log->info('联通通知参数' . json_encode($getData) . '返回参数' . json_encode($res));
        if (!empty($res['code']) && $res['code'] == 200) {
            return true;
        }
        return false;
    }

}
